package judesart.app.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import judesart.app.client.controller.GalleryController;
import judesart.app.domain.Artwork;
import judesart.app.domain.ArtworkPhoto;
import judesart.app.domain.Gallery;
import judesart.app.domain.Room;
import judesart.app.domain.RoomArtwork;
import judesart.app.repository.ArtworkDAO;
import judesart.app.repository.GalleryDAO;
import judesart.app.repository.GalleryDAOImpl;
import judesart.app.util.RegExp;
import judesart.common.bean.ApplicationContextProvider;

/**
 * Servlet implementation class RedirectServlet
 */
public class RedirectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private final static Log LOGGER = LogFactory.getLog(RedirectServlet.class);

	GalleryDAO galleryDAO = ApplicationContextProvider.getCtx().getBean(
			GalleryDAO.class);
	ArtworkDAO artworkDAO = ApplicationContextProvider.getCtx().getBean(
			ArtworkDAO.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RedirectServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String userAgent = request.getHeader("User-Agent");
		String path = request.getPathInfo();
		if (path == null || path.trim().length() < 2) {
			response.sendRedirect("/");
		} else {
			if (userAgent.contains("facebookexternalhit")) {
				if (path.startsWith("/gallery/artwork/")){
					showArtwork(request, response, path);
				} else if (path.startsWith("/gallery/")) {
					showGallery(request, response, path);
				} else if (path.startsWith("/room/")) {
					showRoom(request, response, path);
				} else {
					redirect(response, path);
				}
			} else {
				redirect(response, path);
			}
		}
	}

	private void showRoom(HttpServletRequest request,
			HttpServletResponse response, String path) throws ServletException,
			IOException {
		String roomId = RegExp.matchGroup(path, "/room/(.*)");
		Room room = galleryDAO.findRoomByKey(roomId);
		String title = room.getName();
		String description = room.getDescription();
		Long imageId = null;
		List<RoomArtwork> roomArts = room.getArtworks();
		if (roomArts != null && roomArts.size() > 0) {
			LOGGER.debug("Artworks Found");
			imageId = roomArts.get(0).getMainImageId();
			if (imageId == null) {
				Artwork artwork = artworkDAO.findArtworkById(roomArts
						.get(0).getArtworkId());
				List<ArtworkPhoto> photos = artwork.getPhotos();
				if (photos != null && photos.size() > 0) {
					LOGGER.debug("Photos Found");
					imageId = photos.get(0).getImageId();
				}
			}
		}
		request.setAttribute("title", title);
		request.setAttribute("description", description);
		request.setAttribute("imageId", imageId);
		getServletContext().getRequestDispatcher(
				"/WEB-INF/jsp/resource.jsp").forward(request, response);
	}

	private void showArtwork(HttpServletRequest request,
			HttpServletResponse response, String path) throws ServletException,
			IOException {
		String artworkId = RegExp.matchGroup(path, "/gallery/artwork/(\\d*)");
		Artwork artwork = artworkDAO.findArtworkById(Long.valueOf(artworkId));
		String title = artwork.getTitle();
		String description = artwork.getDescription();
		Long imageId = null;
		List<ArtworkPhoto> photos = artwork.getPhotos();
		if (photos != null && photos.size() > 0) {
			LOGGER.debug("Photos Found");
			imageId = photos.get(0).getImageId();
		}
		request.setAttribute("title", title);
		request.setAttribute("description", description);
		request.setAttribute("imageId", imageId);
		getServletContext().getRequestDispatcher(
				"/WEB-INF/jsp/resource.jsp").forward(request, response);
	}

	private void showGallery(HttpServletRequest request,
			HttpServletResponse response, String path) throws ServletException,
			IOException {
		String galleryId = RegExp.matchGroup(path, "/gallery/(\\d*)");
		Gallery gallery = galleryDAO.findGalleryById(Long.valueOf(galleryId));
		if (gallery != null) {
			String title = gallery.getTitle();
			String description = gallery.getDescription();
			Long imageId = null;
			List<Room> rooms = gallery.getRooms();
			if (rooms != null && rooms.size() > 0) {
				LOGGER.debug("Rooms found");
				List<RoomArtwork> roomArts = rooms.get(0).getArtworks();
				if (roomArts != null && roomArts.size() > 0) {
					LOGGER.debug("Artworks Found");
					imageId = roomArts.get(0).getMainImageId();
					if (imageId == null) {
						Artwork artwork = artworkDAO.findArtworkById(roomArts
								.get(0).getArtworkId());
						List<ArtworkPhoto> photos = artwork.getPhotos();
						if (photos != null && photos.size() > 0) {
							LOGGER.debug("Photos Found");
							imageId = photos.get(0).getImageId();
						}
					}
				}
			}
			LOGGER.debug("Image Id: [" + imageId + "]");
			request.setAttribute("title", title);
			request.setAttribute("description", description);
			request.setAttribute("imageId", imageId);
			getServletContext().getRequestDispatcher(
					"/WEB-INF/jsp/resource.jsp").forward(request, response);
		} else {
			redirect(response, path);
		}
	}

	private void redirect(HttpServletResponse response, String path)
			throws IOException {
		if (path.startsWith("/")) {
			path = path.substring(1);
		}
		response.sendRedirect("/#" + path);
	}

}
